<?php

namespace app\award;

use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\Product;
use app\models\product\ProductAreaList;
use app\models\Queue;
use app\models\SetProductCommission;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserAddress;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\models\UserBalance;
use app\models\UserStore;
use app\models\UserStoreLog;
use app\services\Chain;
use yii\helpers\ArrayHelper;

class AwardOld
{
    protected $user;
    protected $order;
    protected $set;

    protected $items;

    // 总金额
    protected $amount;

    // 是否为第三单
    protected $is_third = false;

    // 如果是777, 不给分红
    protected $is_777 = false;

    protected $is_bao = false;
    protected $is_repeat = false;


    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $order->user_id]);
        $this->set = SetUserUp::getLastOne();


        $this->items = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->all();

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $this->order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();
        $product_id = $first_order_item->product_id;

        $this->amount = $this->order->total_pay - $this->order->total_freight;

        // 报单区
        $this->is_bao = ProductAreaList::checkInArea($product_id, Product::$areaMap['REPORT']);
        if ($this->is_bao) {

            $this->bao();

            // 如果是推三返一, 就不给
            if (!$this->is_third && !$this->is_777) {
                // 分红, 星级福利
                $this->profit();
                $this->welfare();
            }
        }

        // 复购区
        // 复购从平台走, 有差价奖, 没有同级奖
        $this->is_repeat = ProductAreaList::checkInArea($product_id, Product::$areaMap['REPEAT']);
        if ($this->is_repeat) {
            $this->repeat();
        }

        if ($this->is_bao || $this->is_repeat) {
            $this->area();
        }
    }

    // 市代奖
    public function area()
    {
        // 订单如果用了消费积分, 则不返奖
        if ($this->order->use_platform_ticket > 0) {
            return;
        }

        // 计算佣金
        $amount = 0;
        $amount2 = 0;
        foreach ($this->items as $item) {
            $product = SetProductCommission::findOne(['product_id' => $item['product_id']]);
            if ($this->is_bao) {
                $amount += $product['n1'] * $item['price'] / 100 * $item['quantity'];
                $amount2 += $product['n11'] * $item['price'] / 100 * $item['quantity'];
            } else {
                $amount += $product['n2'] * $item['price'] / 100 * $item['quantity'];
                $amount2 += $product['n22'] * $item['price'] / 100 * $item['quantity'];
            }
        }

        // 找出市代
        $address = UserAddress::find()
            ->where(['id' => $this->order->user_address])
            ->andWhere(['user_id' => $this->user->id])
            ->one();
        if ($address) {
            $province_id = $address->province_id;
            $city_id = $address->city_id;
            $area_id = $address->area_id;

            $users = User::find()
                // ->where(['level' => UserLevel::$keys['vip2']])
                // 把区放最前面, 可能只返1个人
                // ->andWhere(['address_up' => [$area_id, $city_id, $province_id]])
                // 这里只查市
                ->andWhere(['address_up' => [$city_id]])
                ->andWhere(['>', 'address_up', 0])
                // 只返1个, 以后允许市和省, 就可以不限制了
                ->limit(1)
                ->all();

            $users2 = User::find()
                // 这里只查区
                ->andWhere(['address_up' => [$area_id]])
                ->andWhere(['>', 'address_up', 0])
                // 只返1个, 以后允许市和省, 就可以不限制了
                ->limit(1)
                ->all();

            // var_dump($users, $amount2);exit;

            // 市代
            if ($users) {
                foreach ($users as $user) {
                    $this->saveCommission($user['id'], $amount,  77, '市代奖');
                }
            }

            // 区代
            if ($users2) {
                foreach ($users2 as $user) {
                    $this->saveCommission($user['id'], $amount2,  78, '区代奖');
                }
            }
        }

    }

    public function repeat()
    {
        $type = 20;
        $name = '复购奖';

        $r1 = Chain::getReferrer($this->user->id, true);
        if ($r1 && $r1->level >= UserLevel::$keys['vip1']) {
            $this->saveCommission($r1->id, $this->amount / 100 * $this->set->repeat_1, $type, $name);

            $r2 = Chain::getReferrer($r1->id, true);
            if ($r2 && $r2->level >= UserLevel::$keys['vip1']) {
                $this->saveCommission($r2->id, $this->amount / 100 * $this->set->repeat_2, $type, $name);

                $r3 = Chain::getReferrer($r2->id, true);
                if ($r3 && $r3->level >= UserLevel::$keys['vip1']) {
                    $this->saveCommission($r3->id, $this->amount / 100 * $this->set->repeat_3, $type, $name);

                    $r4 = Chain::getReferrer($r3->id, true);
                    if ($r4 && $r4->level >= UserLevel::$keys['vip1']) {
                        $this->saveCommission($r4->id, $this->amount / 100 * $this->set->repeat_4, $type, $name);

                        $r5 = Chain::getReferrer($r4->id, true);
                        if ($r5 && $r5->level >= UserLevel::$keys['vip1']) {
                            $this->saveCommission($r5->id, $this->amount / 100 * $this->set->repeat_5, $type, $name);

                            $r6 = Chain::getReferrer($r5->id, true);
                            if ($r6 && $r6->level >= UserLevel::$keys['vip1']) {
                                $this->saveCommission($r6->id, $this->amount / 100 * $this->set->repeat_6, $type, $name);
                            }
                        }
                    }
                }
            }
        }
    }

    // 这个是22链动
    private function _bao22($r)
    {
        $award_name1 = '推荐奖';
        $award_type1 = 31;
        $award_name2 = '间荐奖';
        $award_type2 = 32;

        // 必须要有身份
        if ($r && $r->level >= UserLevel::$keys['vip1']) {

            // 他这里写了两个身份, 实际奖金是一样的

            // 代理
            if ($r->level == UserLevel::$keys['vip1']) {
                if ($r->vip >= 1) {
                    $commission = $this->set->vip1_1 + $this->set->vip1_n_2;
                    $commission = $commission * $this->amount / 100;
                    $commission -= $this->thankful($commission, $r, UserLevel::$keys['vip1']);
                    $this->saveCommission($r->id, $commission, $award_type1, $award_name1);
                } else {
                    $commission = $this->set->vip1_1;
                    $commission = $commission * $this->amount / 100;
                    $commission -= $this->thankful($commission, $r, UserLevel::$keys['vip1']);
                    $this->saveCommission($r->id, $commission, $award_type1, $award_name1);

                    $r2 = $this->getIndirect($r->id);
                    if ($r2) {
                        $commission = $this->set->vip1_n_2;
                        $commission = $commission * $this->amount / 100;
                        $commission -= $this->thankful($commission, $r2, UserLevel::$keys['vip1']);
                        $this->saveCommission($r2->id, $commission, $award_type2, $award_name2);
                    }
                }
            }

            // 加盟商 [分公司]
            if ($r->level >= UserLevel::$keys['vip2']) {
                if ($r->vip >= 1) {
                    $commission = $this->set->vip2_1 + $this->set->vip2_n_2;
                    $commission = $commission * $this->amount / 100;
                    $commission -= $this->thankful($commission, $r, UserLevel::$keys['vip1']);
                    $this->saveCommission($r->id, $commission, $award_type1, $award_name1);
                } else {
                    $commission = $this->set->vip2_1;
                    $commission = $commission * $this->amount / 100;
                    $commission -= $this->thankful($commission, $r, UserLevel::$keys['vip1']);
                    $this->saveCommission($r->id, $commission, $award_type1, $award_name1);

                    $r2 = $this->getIndirect($r->id);
                    if ($r2) {
                        $commission = $this->set->vip2_n_2;
                        $commission = $commission * $this->amount / 100;
                        $commission -= $this->thankful($commission, $r2, UserLevel::$keys['vip1']);
                        $this->saveCommission($r2->id, $commission, $award_type2, $award_name2);
                    }
                }
            }
        }
    }

    public function bao()
    {
        $r = Chain::getReferrer($this->user->id, true);

        if ($this->amount >= $this->set->vip2) {
            $this->_baoVip2($r);
        } else if ($this->amount >= $this->set->vip1) {
            // $this->_baoVip1($r);
            $this->_bao22($r);
            $this->is_777 = true;
        }
    }

    // 废弃
    // private function _baoVip1($r)
    // {
    //     $type = 10;
    //     $name = '直推';
    //     $type2 = 11;
    //     $name2 = '间推';
    //
    //     if ($r && $r->level >= UserLevel::$keys['vip1']) {
    //         // 有没有推2单(不包含正下单的)
    //         $has_2 = (int)User::find()
    //             ->where(['referrer_id' => $r->id])
    //             ->andWhere(['>=', 'level', UserLevel::$keys['vip1']])
    //             ->count();
    //
    //         if ($r->level >= UserLevel::$keys['vip2']) {
    //             if ($has_2 >= 2) {
    //                 // 第3+单
    //                 $commission = $this->set->vip2_n_1 + $this->set->vip2_n_2;
    //                 $commission = $commission * $this->amount / 100;
    //                 // 减去感恩
    //                 $commission -= $this->thankful($commission, $r, UserLevel::$keys['vip2']);
    //                 $this->saveCommission($r->id, $commission, $type, $name);
    //             } else {
    //                 $commission = $this->set->vip2_1;
    //                 $commission = $commission * $this->amount / 100;
    //
    //                 // 间推奖
    //                 $r2 = $this->getIndirect($r->id);
    //                 if ($r2) {
    //                     $commission2 = $this->set->vip2_n_2;
    //                     $commission2 = $commission2 * $this->amount / 100;
    //                     // 减去感恩
    //                     $commission2 -= $this->thankful($commission2, $r2, UserLevel::$keys['vip2']);
    //                     $this->saveCommission($r2->id, $commission2, $type2, $name2);
    //                 } else {
    //                     // 没有r2, 则用r1来处理感恩奖
    //                     // 减去感恩
    //                     $commission -= $this->thankful($commission, $r, UserLevel::$keys['vip2']);
    //                 }
    //
    //                 $this->saveCommission($r->id, $commission, $type, $name);
    //
    //             }
    //         } else {
    //             // 代理 直推
    //             if ($has_2 >= 2) {
    //                 // 第3+单
    //                 $commission = $this->set->vip1_n_1;
    //                 $commission = $commission * $this->amount / 100;
    //
    //                 // 间推
    //                 $r2 = $this->getIndirect($r->id);
    //                 if ($r2) {
    //                     $commission2 = $this->set->vip1_n_2;
    //                     $commission2 = $commission2 * $this->amount / 100;
    //                     // 减去感恩
    //                     $commission2 -= $this->thankful($commission2, $r2, UserLevel::$keys['vip1']);
    //                     $this->saveCommission($r2->id, $commission2, $type2, $name2);
    //                 } else {
    //                     // 没有r2, 则用r1来处理感恩奖
    //                     // 减去感恩
    //                     $commission -= $this->thankful($commission, $r, UserLevel::$keys['vip1']);
    //                 }
    //
    //                 $this->saveCommission($r->id, $commission, $type, $name);
    //             } else {
    //                 $commission = $this->set->vip1_1;
    //                 $commission = $commission * $this->amount / 100;
    //
    //                 // 间推
    //                 $r2 = $this->getIndirect($r->id);
    //                 if ($r2) {
    //                     $commission2 = $this->set->vip1_n_2;
    //                     $commission2 = $commission2 * $this->amount / 100;
    //                     // 减去感恩
    //                     $commission2 -= $this->thankful($commission2, $r2, UserLevel::$keys['vip1']);
    //                     $this->saveCommission($r2->id, $commission2, $type2, $name2);
    //                 } else {
    //                     // 没有r2, 则用r1来处理感恩奖
    //                     // 减去感恩
    //                     $commission -= $this->thankful($commission, $r, UserLevel::$keys['vip1']);
    //                 }
    //
    //                 $this->saveCommission($r->id, $commission, $type, $name);
    //             }
    //         }
    //     }
    // }

    // 感恩
    public function thankful($amount, $r, $level)
    {
        $type = 101;
        $name = '感恩奖';

        // 扣除总数
        $sum = 0;

        // 只找直推和间推了, 不管等级

        // $user = $this->getIndirect($r->id);
        // $user = Chain::getReferrerChainOne($r->id, [$level], true);
        // $user = Chain::getReferrer($r->id, true);
        // if ($user && $user->level >= UserLevel::$keys['vip1']) {
        //     $commission = $amount * $this->set->v1 / 100;
        //     $this->saveCommission($user->id, $commission, $type, $name);
        //
        //     $sum += $commission;
        //
        //     // $user2 = $this->getIndirect($user->id);
        //     // $user2 = Chain::getReferrerChainOne($user->id, [$level], true);
        //     $user2 = Chain::getReferrer($user->id, true);
        //     if ($user2 && $user2->level >= UserLevel::$keys['vip1']) {
        //         $commission = $amount * $this->set->v2 / 100;
        //         $this->saveCommission($user2->id, $commission, $type, $name);
        //
        //         $sum += $commission;
        //     }
        // }

        $chain = Chain::getReferrerChain($r->id, [], true);
        $len = count($chain);
        // 返6层
        for ($i = 0; $i <= 6 && $i < $len; $i++) {
            if ($chain[$i]['level'] < UserLevel::$keys['vip1']) {
                break;
            }
            // $ratio = 0;
            if ($i + 1 == 1) {
                $ratio = $this->set->v1;
            }
            if ($i + 1 == 2) {
                $ratio = $this->set->v2;
            }
            if ($i + 1 == 3) {
                $ratio = $this->set->v3;
            }
            if ($i + 1 == 4) {
                $ratio = $this->set->v4;
            }
            if ($i + 1 == 5) {
                $ratio = $this->set->v5;
            }
            if ($i + 1 == 6) {
                $ratio = $this->set->v6;
            }
            $commission = $amount * $ratio / 100;
            $this->saveCommission($chain[$i]['id'], $commission, $type, $name);

            $sum += $commission;
        }

        return $sum;
    }

    private function _baoVip2($r)
    {
        // todo 已经取消了消费积分
        // 01-16

        $type = 20;
        $name = '直推';

        if ($r && $r->level >= UserLevel::$keys['vip1']) {
            $ids = User::find()
                ->where(['referrer_id' => $r->id])
                ->select(['id'])
                ->column();

            // 会加上本条订单的
            $order_count = Order::find()
                ->where(['user_id' => $ids])
                ->andWhere(['>=', 'total_pay', $this->set->vip2])
                ->andWhere(['!=', 'status', Order::$statusMapping['CANCEL']])
                ->andWhere(['!=', 'status', Order::$statusMapping['NON_PAYMENT']])
                ->andWhere(['!=', 'status', Order::$statusMapping['DELETE']])
                ->count();

            // var_dump(intval($order_count));exit;

            // 推三返一
            $sub_score = true;
            if (intval($order_count) % 3 == 0) {

                // 第三单不分红
                $this->is_third = true;
                $this->is_third = false;

                $ratio = $this->set->vip2_n;
                $sub_score = true;
            } else {
                // $ratio = $this->set->vip2_2;
                $ratio = $this->set->vip2_n;
            }

            $commission = $ratio * $this->amount / 100;

            // 减去积分
            $score = 0;
            if ($sub_score) {
                $score = $this->set->score / 100 * $commission;
                // $commission -= $score;
            }

            // 减去感恩奖
            $commission -= $this->thankful($commission, $r, UserLevel::$keys['vip2']);

            // 消费积分
            if ($score > 0) {
                // $this->saveScore($r->id, $score, $type, $name);
            }

            if ($r->level < UserLevel::$keys['vip2']) {
                $status = 0;
            } else {
                $status = 1;
            }

            $this->saveCommission($r->id, $commission, $type, $name, $status);
        }
    }

    // 分红
    public function profit()
    {
        // 必须是6星才有分红

        $type = 1;
        $name = '分红';

        $users = User::find()
            ->where(['>=', 'level', UserLevel::$keys['vip2']])
            ->andWhere(['star' => 6])
            ->all();

        $count = count($users);

        if ($count > 0) {
            $commission = $this->amount * $this->set->profit / $count / 100;
            foreach ($users as $user) {
                $this->saveCommission($user->id, $commission, $type, $name);
            }
        }

    }

    // 福利
    public function welfare()
    {
        $chain = Chain::getReferrerChain($this->user->id, [
            UserLevel::$keys['vip1'],
            UserLevel::$keys['vip2'],
            UserLevel::$keys['vip3']
        ]);
        $chain = ArrayHelper::getColumn($chain, 'id');
        if ($chain) {
            // 这里要处理下排序, 否则顺序有问题
            $users = [];
            foreach ($chain as $item) {
                $user = User::find()
                    ->where(['id' => $item])
                    ->andWhere(['>=', 'star', 1])
                    ->one();
                if ($user) {
                    $users[$item] = $user;
                }
            }
            $this->_welfare($users);
        }
    }

    private function _welfare($users)
    {
        $type = 2;
        $name = '福利';

        $has_star1 = false;
        $has_star2 = false;
        $has_star3 = false;
        $has_star4 = false;
        $has_star5 = false;
        $has_star6 = false;

        $diff_star1 = 0;
        $diff_star2 = 0;
        $diff_star3 = 0;
        $diff_star4 = 0;
        $diff_star5 = 0;
        $diff_star6 = 0;

        $amount = $this->amount / 100;

        foreach ($users as $user) {
            if ((!$has_star1 && !$has_star2 && !$has_star3 && !$has_star4 && !$has_star5 && !$has_star6) && $user->star == 1) {
                $diff_star1 = $amount * $this->set->s1;
                $this->saveCommission($user->id, $diff_star1, $type, $name);
                $has_star1 = true;
            }
            if ((!$has_star2 && !$has_star3 && !$has_star4 && !$has_star5 && !$has_star6) && $user->star == 2) {
                $diff_star2 = $amount * $this->set->s2;
                $diff_star2 -= $diff_star1;
                $this->saveCommission($user->id, $diff_star2, $type, $name);
                $has_star2 = true;
            }
            if ((!$has_star3 && !$has_star4 && !$has_star5 && !$has_star6) && $user->star == 3) {
                $diff_star3 = $amount * $this->set->s3;
                $diff_star3 -= $diff_star1 + $diff_star2;
                $this->saveCommission($user->id, $diff_star3, $type, $name);
                $has_star3 = true;
            }
            if ((!$has_star4 && !$has_star5 && !$has_star6) && $user->star == 4) {
                $diff_star4 = $amount * $this->set->s4;
                $diff_star4 -= $diff_star1 + $diff_star2 + $diff_star3;
                $this->saveCommission($user->id, $diff_star4, $type, $name);
                $has_star4 = true;
            }
            if ((!$has_star5 && !$has_star6) && $user->star == 5) {
                $diff_star5 = $amount * $this->set->s5;
                $diff_star5 -= $diff_star1 + $diff_star2 + $diff_star3 + $diff_star4 ;
                $this->saveCommission($user->id, $diff_star5, $type, $name);
                $has_star5 = true;
            }
            if ((!$has_star6) && $user->star == 6) {
                $diff_star6 = $amount * $this->set->s6;
                $diff_star6 -= $diff_star1 + $diff_star2 + $diff_star3 + $diff_star4 + $diff_star5 ;
                $this->saveCommission($user->id, $diff_star6, $type, $name);
                $has_star6 = true;
                break;
            }
        }
    }

    // 这个是平级就行,
    // 主要是找有没有推两个的人
    private function getIndirect($user_id)
    {
        $the_referrer = Chain::getReferrer($user_id, true);
        if (!$the_referrer) {
            return null;
        }

        // 高等级
        if ($the_referrer->level >= UserLevel::$keys['vip2']) {
            // 她的不截断
            // return $the_referrer;
        }

        // 处理两线条
        if ($the_referrer->level >= UserLevel::$keys['vip1']) {

            // 判断是否属于前2个直推
            $children = Chain::getChildrenSort($the_referrer->id, ['id']);

            // if (count($children) > $this->set->vip2) {
            if (count($children) > 2) {
                $children = [$children[0], $children[1]];
                $in = in_array($user_id, $children);
                if (!$in) {
                    return $the_referrer;
                } else {
                    return $this->getIndirect($the_referrer->id);
                }
            } else {
                return $this->getIndirect($the_referrer->id);
            }
        }

        return $this->getIndirect($the_referrer->id);
    }

    // 保存佣金 (await balance)
    protected function saveCommission($user_id, $balance, $type, $name, $status = 1)
    {
        if ($balance >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->order->user_id;
            $model->order_id = $this->order->id;
            $model->balance = $balance;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->save();
            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                if ($status == 1) {
                    $account->balance += $balance;
                } else {
                    $account->await_balance += $balance;
                }

                $account->save();
            }

            // balance logs
            if ($status == 1) {
                UserBalance::addLog($model->user_id,
                    $account->balance, $model->balance, $account->balance + $model->balance, '返佣', $this->order->id);
            }
        }
    }

    protected function saveScore($user_id, $platform_ticket, $type, $name, $status = 1)
    {
        if ($platform_ticket >= 0.01) {
            $model = new UserCommission();
            $model->user_id = $user_id;
            $model->fans_id = $this->order->user_id;
            $model->order_id = $this->order->id;
            $model->balance = 0;
            $model->status = $status;
            $model->award_name = $name;
            $model->award_type = $type;
            $model->platform_ticket = $platform_ticket;
            $model->save();

            $account = UserAccount::findOne(['user_id' => $user_id]);
            if ($account) {
                $account->platform_ticket += $platform_ticket;
                $account->save();
            }
        }
    }
}